package ssm.shopping.aop;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import ssm.shopping.commons.SysContent;

@Aspect
@Component("logAspect")
public class LogAspectTest {

	private static final Logger logger = LoggerFactory.getLogger(LogAspectTest.class);

	@Pointcut("@annotation(ssm.shopping.aop.BusAnnotion)")
	private void deal() {}

	/**
	 * @Description: 方法调用前触发
	 * @param joinPoint
	 */
	@Around("deal()")
	public Object before(ProceedingJoinPoint joinPoint) {

		// 先执行业务
		Object obj = "";
		
		// 获取request,response，session
		HttpServletRequest request = SysContent.getRequest();
		HttpServletResponse response = SysContent.getResponse();
		HttpSession session = request.getSession();
		
		logger.info("request--->"+request);
		logger.info("response--->"+response);
		logger.info("session--->"+session);

		// 获取拦截的方法名
		Signature signature = joinPoint.getSignature();
		MethodSignature methodSignature = (MethodSignature) signature;

		// 获取自定义注解的参数（相当于new了一个BusAnnotion对象）
		BusAnnotion busAnnotion = methodSignature.getMethod().getAnnotation(BusAnnotion.class);

		if (busAnnotion.businessType() == 0) {
			logger.info("不处理session");
		}

		if (busAnnotion.businessType() == 1) {
			if (null != session.getAttribute("sessionId")) {
				// 说明登陆过了 无需登陆
			}
		}

		logger.info(String.format("session--> %s,businessType--> %d",
				session.getAttribute("sessionId"), busAnnotion.businessType()));

		if (busAnnotion.businessType() == 2) {
			if (null == session.getAttribute("sessionId")) {
				// 说明没有登陆 提示需要登陆
				
			}
		}

		try {// 先执行业务
			obj = joinPoint.proceed();
		} catch (Throwable e) {
			logger.error(e.getMessage());
		}

		/**
		 * 处理日志
		 */
		try {
			// 获取方法的参数名称
			String[] parameterNames = methodSignature.getParameterNames();
			for (int i = 0; i < parameterNames.length; i++) {
				logger.info("parameterNames--->" + parameterNames[i]);
			}
			// 获取方法的参数值
			Object[] args = joinPoint.getArgs();
			for (int k = 0; k < args.length; k++) {
				Object arg = args[k];
				logger.info("args:" + arg);
				// 获取参数类型
				String typeName = arg.getClass().getTypeName();
				logger.info("typeName:" + typeName);
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}

		return obj;
		// 记录日志到数据库
	}
}
